iT邦幫忙

2022 iThome 鐵人賽

DAY 5
0
自我挑戰組

30天 Neetcode解題之路系列 第 5

Day 5 - 1. Two Sum

  • 分享至 

  • xImage
  •  

前言

大家好,我是毛毛。ヾ(´∀ ˋ)ノ
那就開始今天的解題吧~


Question

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

Constraints:

  • 2 <= nums.length <= 10^4
  • -10^9 <= nums[i] <= 10^9
  • -10^9 <= target <= 10^9.
  • Only one valid answer exists.

Follow up: Can you come up with an algorithm that is less than O(n2) time complexity?

Think

從陣列中找出兩個值加總為target,並回傳兩個值的index。

用一個count_dict來存每個數字出現的字數,最後找出dictionary中values()最大值的index,再透過index找出對應的key值,重複這個步驟k次。

Code

  • 暴力解
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        remain = 0
        
        for num1 in range(len(nums)-1):
            remain = target - nums[num1]
            for num2 in range(num1+1, len(nums)):
                if remain == nums[num2]:
                    return [num1,num2]
 
  • 另解
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        remain = 0
                
        num_dict = {}
        for index, num in enumerate(nums):
            remain = target - num
            if remain in num_dict:
                return [num_dict[remain], index]
            num_dict[num] = index
        
        

Submission

  • 暴力解

  • 另解


今天就到這邊啦~
大家明天見/images/emoticon/emoticon29.gif


上一篇
Day 4 - 347. Top K Frequent Elements
下一篇
Day 6 - 238. Product of Array Except Self
系列文
30天 Neetcode解題之路30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言